package com.uobgroup.ews.uam.web;

import com.uobgroup.ews.uam.core.domain.SecurityGroup;
import com.uobgroup.ews.uam.core.service.SecurityGroupService;
import com.uobgroup.ews.uam.web.validation.SecurityGroupValidator;

import java.io.UnsupportedEncodingException;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.util.UriUtils;
import org.springframework.web.util.WebUtils;

@RequestMapping("/securitygroups")
@Controller
public class SecurityGroupController {

   @Autowired
   SecurityGroupService securityGroupService;

   @Autowired
   SecurityGroupValidator securityGroupValidator;

   @InitBinder
   protected void InitBinder(WebDataBinder binder){
      binder.setValidator(securityGroupValidator);
   }

   @RequestMapping(method = RequestMethod.POST, produces = "text/html")
   public String create(@Valid SecurityGroup securityGroup, BindingResult bindingResult, Model uiModel,
         HttpServletRequest httpServletRequest) {
      if (bindingResult.hasErrors()) {
         populateEditForm(uiModel, securityGroup);
         return "securitygroups/create";
      }
      uiModel.asMap().clear();
      securityGroupService.saveSecurityGroup(securityGroup);
      return "redirect:/securitygroups/" + encodeUrlPathSegment(securityGroup.getId().toString(), httpServletRequest);
   }

   @RequestMapping(value = "/create", produces = "text/html", method = RequestMethod.GET)
   public String createForm(Model uiModel) {
      populateEditForm(uiModel, new SecurityGroup());
      return "securitygroups/create";
   }

   @RequestMapping(value = "/{id}", produces = "text/html")
   public String show(@PathVariable("id") Long id, Model uiModel) {
      uiModel.addAttribute("securitygroup", securityGroupService.findSecurityGroup(id));
      uiModel.addAttribute("itemId", id);
      return "securitygroups/show";
   }

   @RequestMapping(produces = "text/html")
   public String list(@RequestParam(value = "page", required = false) Integer page,
         @RequestParam(value = "size", required = false) Integer size, Model uiModel) {
      String forward = listSecurityGroups(page, size, uiModel);
      return forward;
   }

   @RequestMapping(method = RequestMethod.PUT, produces = "text/html")
   public String update(@Valid SecurityGroup securityGroup, BindingResult bindingResult, Model uiModel,
         HttpServletRequest httpServletRequest) {
      if (bindingResult.hasErrors()) {
         populateEditForm(uiModel, securityGroup);
         return "securitygroups/update";
      }
      uiModel.asMap().clear();
      securityGroupService.updateSecurityGroup(securityGroup);
      return "redirect:/securitygroups/" + encodeUrlPathSegment(securityGroup.getId().toString(), httpServletRequest);
   }

   @RequestMapping(value = "/update/{id}", produces = "text/html")
   public String updateForm(@PathVariable("id") Long id, Model uiModel) {
      populateEditForm(uiModel, securityGroupService.findSecurityGroup(id));
      return "securitygroups/update";
   }

   @RequestMapping(value = "/{id}", method = RequestMethod.DELETE, produces = "text/html")
   public String delete(@PathVariable("id") Long id, @RequestParam(value = "page", required = false) Integer page,
         @RequestParam(value = "size", required = false) Integer size, Model uiModel) {
      SecurityGroup securityGroup = securityGroupService.findSecurityGroup(id);
      boolean hasError = securityGroupValidator.validateDelete(securityGroup, uiModel);
      if (!hasError) {
         securityGroupService.deleteSecurityGroup(securityGroup);
         uiModel.asMap().clear();
      }
      String forward = listSecurityGroups(((page == null) ? 1 : page),((size == null) ? 1 : size), uiModel);
      return forward;
   }

   public String listSecurityGroups(Integer page, Integer size, Model uiModel) {
      if (page != null || size != null) {
         int sizeNo = size == null ? 10 : size.intValue();
         final int firstResult = page == null ? 0 : (page.intValue() - 1) * sizeNo;
         uiModel.addAttribute("securitygroups", securityGroupService.findSecurityGroupEntries(firstResult, sizeNo));
         float nrOfPages = (float) securityGroupService.countAllSecurityGroups() / sizeNo;
         uiModel.addAttribute("maxPages", (int) ((nrOfPages > (int) nrOfPages || nrOfPages == 0.0) ? nrOfPages + 1
               : nrOfPages));
      } else {
         uiModel.addAttribute("securitygroups", securityGroupService.findAllSecurityGroups());
      }
      return "securitygroups/list";
   }

   void populateEditForm(Model uiModel, SecurityGroup securityGroup) {
      uiModel.addAttribute("securityGroup", securityGroup);
   }

   String encodeUrlPathSegment(String pathSegment, HttpServletRequest httpServletRequest) {
      String enc = httpServletRequest.getCharacterEncoding();
      if (enc == null) {
         enc = WebUtils.DEFAULT_CHARACTER_ENCODING;
      }
      try {
         pathSegment = UriUtils.encodePathSegment(pathSegment, enc);
      } catch (UnsupportedEncodingException uee) {
      }
      return pathSegment;
   }
}
